
package com.principle.flyweight;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 享元模式
 * 
 * @author zhonghong.zhangxg
 * @date 2016年7月15日上午10:09:55
 */
public class TicketFactory {

    /** 未使用享元模式 */
    // public static ITicket getTicket(String from, String to) {
    // return new TrainTicket(from, to);
    // }

    /** 享元模式通过消息池的模式有效减少了重复对象的存在 */
    static Map<String, ITicket> sTicketMap = new ConcurrentHashMap<String, ITicket>();

    public static ITicket getTicket(String from, String to) {
        String key = from + "-" + to;
        if (sTicketMap.containsKey(key)) {
            return sTicketMap.get(key);
        } else {
            ITicket ticket = new TrainTicket(from, to);
            sTicketMap.put(key, ticket);
            return ticket;
        }
    }
}
